var app = getApp();
var ConstantData = require('../../common/constant_data.js')

function toWxNoDepositLeasePage(extraData, outOrderCode, that) {

  console.log("toWxNoDeposit-->", extraData);

  that.data.queryNoDepositTimer = setTimeout(function () {
    if (that.data.checkPayStatusInterval) { //先清除定时器防止产生多个
      clearInterval(that.data.checkPayStatusInterval)
    }
    that.data.checkPayStatusInterval = setInterval(() => {
      console.log('【轮询免押状态】', that.data.isNoDepositSuccess, that.data.pileState);
      if (that.data.isNoDepositSuccess) {
        if (that.data.checkPayStatusInterval) {
          clearInterval(that.data.checkPayStatusInterval);
        }
        that.data.checkPayStatusInterval = null
        return;
      }

      //查询订单结果判断并开锁
      queryOrderStatus(null, that, outOrderCode, that.data.pileState);
    }, 1000);
  }, 10000)

  wx.navigateToMiniProgram({
    appId: "wxd8f3793ea3b935b8",
    path: "pages/use/use",
    extraData: {
      "mch_id": extraData.mch_id,
      "package": extraData.package,
      "timestamp": extraData.timestamp,
      "nonce_str": extraData.nonce_str,
      "sign_type": extraData.sign_type,
      "sign": extraData.sign
    },
    success() {
      clearInterval(app.globalData.noDepositTimer)
    },
    fail(res) {
      that.recordBlueConnectError(ConstantData.err_type.deposit_to_noDepositFail, '跳转免押失败' + JSON.stringify(res))
    }
  })
}

function getLeaseNoDepositInfo(res, that, onLoadFlg, pileState) {
  console.log("getNodepositInfo-->", res, that.data.noDepositBackFlg, that.data.pt, that.data.cur_act);
  getApp().hideLoading();
  if (res && (res.scene === 1038 || res.scene === 1001) && !that.data.noDepositBackFlg) { // 场景值1038：从被打开的小程序返回
    //防止用户未退出界面再次归还，造成重复调用
    that.setData({
      noDepositBackFlg: true
    })
    const {
      appId,
      extraData
    } = res.referrerInfo
    if (extraData == undefined || extraData == null) {
      that.setData({
        isWXScore: 0
      })
      clearInterval(that.data.checkPayStatusInterval);
      depositLease(that);
      return;
    }
    if (appId === 'wxd8f3793ea3b935b8') { //appId为【创建租借订单】返回的miniprogram_appid：从签约小程序跳转回来，建议检查，不强制
      let query_id = extraData.query_id
      if (!query_id) {
        depositLease(that);
      } else {
        //查询订单结果判断并开锁
        queryOrderStatus(query_id, that, onLoadFlg, pileState);
      }
    } else {
      depositLease(that);
    }
  } else if (!that.data.noDepositBackFlg) {
    console.log("------->noDepositBackFlg-false")

    that.setData({
      noDepositBackFlg: true
    })
    depositLease(that)
  } else if (that.data.pt != 'noback' && that.data.pt != 'noreturnequ' && that.data.cur_act != 'scan') {
    //不是从使用中的页面扫码跳转过来的
    let noBackRes = wx.getStorageSync("user_no_back")
    let noPayRes = wx.getStorageSync("user_no_pay")
    console.log('-------------------------------------------------------------------------------->>', noBackRes, onLoadFlg)
    console.log('-------------------------------------------------------------------------------->>', noPayRes, onLoadFlg)
    if (onLoadFlg && onLoadFlg == 1) {
      return
    }
    if (noBackRes && noBackRes.data.noBack) {
      console.log("---aa---noBack", noBackRes)
      console.log("---aa---noBack--pt=", that.data.pt)
      //未归还的
      wx.navigateTo({
        url: './no_back_tip/no_back_tip?equId=' + noBackRes.data.noBack.equId + "&positions=" + noBackRes.data.noBack.positions + "&hospitalName=" + noBackRes.data.noBack.hospitalName + "&orderCode=" + noBackRes.data.noBack.leaseOrderCode,
      })
      return
    } else if (noPayRes && noPayRes.data.noPay) {
      console.log("-------------------------------aa---noPay", noPayRes)
      //未支付
      let rentInfo = {};
      rentInfo.backTime = noPayRes.data.noPay.backTime;
      rentInfo.borrowTime = noPayRes.data.noPay.borrowTime;
      rentInfo.costTime = noPayRes.data.noPay.costTime;
      rentInfo.deposit = noPayRes.data.noPay.deposit;
      rentInfo.orderCode = noPayRes.data.noPay.orderCode;
      rentInfo.rent = noPayRes.data.noPay.rent;
      rentInfo.noPayTitle = noPayRes.data.noPay.noPayTitle;
      rentInfo.priceLabel = noPayRes.data.noPay.priceLabel;
      rentInfo.orderType = noPayRes.data.noPay.orderType;
      rentInfo.equId = noPayRes.data.noPay.equId || 0;
      rentInfo.inCycleLeaseTimeLen = noPayRes.data.noPay.inCycleLeaseTimeLen || '';
      rentInfo.inCycleRecordInfoList = noPayRes.data.noPay.inCycleRecordInfoList || [];
      rentInfo.noPayDepositTip = noPayRes.data.noPay.noPayDepositTip;
      wx.navigateTo({
        url: './no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
      })
      return
    }
  } else {
    that.setData({
      openning_show: false
    })
  }
}
//走押金租借
function depositLease(that) {
  //信用免押需要取消订单
  noSureCancelOrder(that);
  //继续走押金支付
  that.setData({
    openning_show: false,
    toPayDeposit: true,
    isPayDeposit: false,
    noDepositFail: true //免押租借
  })
  that.data.isWXScore = 0
  that.showLeaseRule()
}

/**
 * 查询订单状态函数
 * 由商家后台服务提供
 * @param query_id {String} 单据id，可以在接口【查询租借订单】进行单据查询
 */
function queryOrderStatus(query_id, that, outOrderCode, pileState) {
  console.log('查询订单状态', that.data.cancelNoDeposit)
  let now = new Date().getTime()
  let isOpen = !that.data.openTime || now - that.data.openTime > 60000

  if (that.data.cancelNoDeposit === true) {
    that.data.cancelNoDeposit = false
    clearInterval(that.data.checkPayStatusInterval)
    return
  }

  if (that.showStatInfo && that.data.statVal && isOpen) {
    that.showStatInfo(that.data.statVal.queryNoDeposit)
  }
  // 商家小程序向商家后台服务请求查询订单状态，
  // 这里的前后端接口和数据协议由商家侧设计
  // 函数返回查询结果，这里以布尔值true代表租借成功，布尔值false代表租借失败
  //查询到用户若为确定订单，则直接取消订单走押金流程，押金支付成功后再生成订单并开锁
  app.executeRequest(function (header) {
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/wx_no_deposit/query',
      method: 'post',
      header: header,
      data: {
        queryId: query_id,
        isCancelOrder: 1,
        orderCode: outOrderCode ? outOrderCode : ''
      },
      success: function (res) {
        console.log("wxNOdepoist query,", res, isOpen, that.showStatInfo, that.data.statVal, pileState);
        if (res.data.data == 1) {
          clearInterval(that.data.checkPayStatusInterval)

          that.recordBlueConnectError(ConstantData.err_type.deposit_auth_success, '免押授权成功,准备开锁...' + isOpen)
          if (isOpen) {
            that.data.openTime = now
            // 租借成功
            that.setData({
              openning_desc: '免押授权成功,准备开锁...',
              showFreeTipDialog: false
            })
            if (that.showStatInfo && that.data.statVal) {
              that.showStatInfo(that.data.statVal.noDepositOpen)
            }
            that.send85Command()
          }
        } else {
          if (query_id || res.data.data == 2) {
            //只针对用户回退方式的请求使用        
            clearInterval(that.data.checkPayStatusInterval)
            that.setData({
              openning_desc: '免押授权失败,准备支付押金...'
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_auth_fail, '免押授权失败,准备支付押金...')
            depositLease(that);
          }
        }
      },
      fail: function () {
        // 租借失败
        that.setData({
          openning_show: false,
          alertBoxStatus: true,
          alertBoxTipContent: '请重试(' + 1 + ')！'
        })
      }
    })
  });
}

function noSureCancelOrder(that) {
  that.data.cancelNoDeposit = true
  var outOrderCode = wx.getStorageSync('outOrderCode');
  console.log("---noSureCancelOrder-->", outOrderCode);
  // 商家小程序向商家后台服务请求查询订单状态，
  // 这里的前后端接口和数据协议由商家侧设计
  // 函数返回查询结果，这里以布尔值true代表租借成功，布尔值false代表租借失败
  app.executeRequest(function (header) {
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/wx_no_deposit/noSureCancel',
      method: 'post',
      header: header,
      data: {
        orderCode: outOrderCode,
        isCreateOrder: 0 //兼容20190706改动之前的版本，改动后的不需要再生成订单
      },
      success: function (res) {
        console.log("wxNOSureCancel query,", res);
      },
      fail: function (res) {
        console.log("wxNOSureCancel query fail,", res);
      }
    })
  });
}

function queryPayDepositStatus(orderCode) {
  // 查询押金支付状态
  console.log('【查询押金支付状态】订单号：', orderCode);

  return new Promise((reslove, reject) => {
    getApp().executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/isPaySuc',
        method: 'post',
        header: header,
        data: {
          orderCode: orderCode,
        },
        success: function (res) {
          console.log('查询押金支付成功', res);
          if (res && res.data && res.data.data == 'true') {
            reslove('支付成功');
          } else {
            reject('尚未支付');
          }
        },
        fail: function (error) {
          console.log('查询押金支付失败', error);
          reject(error.errMsg);
        }
      });
    });
  });
}

module.exports.toWxNoDepositLeasePage = toWxNoDepositLeasePage
exports.getLeaseNoDepositInfo = getLeaseNoDepositInfo
exports.noSureCancelOrder = noSureCancelOrder
exports.queryPayDepositStatus = queryPayDepositStatus